﻿using Microsoft.AspNetCore.Mvc;
using RabbitMQ.Client;
using RabbitMQ_Common;
using System.Text;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace RabbitMQ_Proider.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TopicController : ControllerBase
    {
        // GET: api/<TopicController>
        [HttpGet]
        public IEnumerable<string> Get()
        {
            using (var connection = RabbitMQHelper.GetConnection())
            {
                using (var channel = connection.CreateModel())//创建信道，通信管道
                {
                    //声明交换机
                    channel.ExchangeDeclare("topic_exchange", "topic");

                    //创建队列
                    var queue = "topic";
                    channel.QueueDeclare(queue, false, false, false, null);//durable等于true时就是消息持久化，用户重启不丢消息
                    var queue2 = "topic2";
                    channel.QueueDeclare(queue2, false, false, false, null);
                    var queue3 = "topic3";
                    channel.QueueDeclare(queue3, false, false, false, null);
                    //绑定交换机,指定routingKey
                    string[] routingKeyList = new string[] { "red.*", "gre.f", "yell.w" };//routingKey在匹配符模式下，可以根据匹配符来发送消息；*代表一个单词，a.*可以是a.b;但不可以为a.b.c;#代表所有，例如a.#，可以是a.b或者a.b.c
                    channel.QueueBind(queue, "topic_exchange", routingKeyList[0]);
                    channel.QueueBind(queue2, "topic_exchange", routingKeyList[1]);
                    channel.QueueBind(queue3, "topic_exchange", routingKeyList[2]);
                    //没绑定交换机，但由于rabbitmq有默认交换机
                    for (var i = 0; i < 10; i++)
                    {
                        //指定发送routingKey
                        string message = "测试1" + i;
                        var body = Encoding.UTF8.GetBytes(message);
                        channel.BasicPublish("topic_exchange", "gre.f", null, body);//这里的routingKey必须为全匹配

                    }


                }
            }
            return new string[] { "ok" };
        }

       
    }
}
